package com.app.utils.barcode;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Hashtable;
import java.util.Map;
import java.util.Vector;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;

import com.barcode.camera.CameraManager;
import com.barcode.decode.BitmapLuminanceSource;
import com.barcode.decode.DecodeFormatManager;
import com.barcode.decode.InactivityTimer;
import com.barcode.decode.IsChineseOrNot;
import com.barcode.view.ViewfinderView;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.utils.main.ImageUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.StringUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.widget.MyDialog;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.ResultMetadataType;
import com.google.zxing.common.HybridBinarizer;
import com.lepu.app.fun.chat.activity.DoctorMyActivity;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;
import com.lepu.pasm.R;

/**
 * 扫描二维码
 * 
 */
@SuppressWarnings("deprecation")
public class CaptureActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, OnTopbarNewRightButtonListener,
		SurfaceHolder.Callback {

	public static final int BACK_PHOTO = 100;

	private boolean mHasSurface;
	private static final String CHARACTER_SET = "ISO-8859-1";

	private ViewfinderView mViewfinderView;
	private ImageButton mFlashImageButton;

	/**
	 * 活动监控器，用于省电，如果手机没有连接电源线，那么当相机开启后如果一直处于不被使用状态则该服务会将当前activity关闭。
	 * 活动监控器全程监控扫描活跃状态，与CaptureActivity生命周期相同.每一次扫描过后都会重置该监控，即重新倒计时。
	 */
	private InactivityTimer mInactivityTimer;
	private CameraManager mCameraManager;
	private Vector<BarcodeFormat> mDecodeFormats;// 编码格式
	private CaptureActivityHandler mHandler;// 解码线程

	private static final Collection<ResultMetadataType> DISPLAYABLE_METADATA_TYPES = EnumSet
			.of(ResultMetadataType.ISSUE_NUMBER,
					ResultMetadataType.SUGGESTED_PRICE,
					ResultMetadataType.ERROR_CORRECTION_LEVEL,
					ResultMetadataType.POSSIBLE_COUNTRY);

	private String mFlag;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		initSetting();
		super.onCreate(savedInstanceState);
		setContentView(R.layout.app_barcode_capture);
		initView();
	}

	/**
	 * 初始化窗口设置
	 */
	private void initSetting() {
		Window window = getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // 保持屏幕处于点亮状态
		// window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); // 全屏
		// requestWindowFeature(Window.FEATURE_NO_TITLE); // 隐藏标题栏
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 竖屏
	}

	/**
	 * 初始化视图
	 */
	private void initView() {

		CustomTopBarNew topBar = (CustomTopBarNew) findViewById(R.id.captureTopBar);
		// topBar.setRightButton(R.drawable.saoyisao_photo_selector);
		topBar.setTopbarTitle("扫一扫");
		topBar.setonTopbarNewLeftLayoutListener(this);
		topBar.setOnTopbarNewRightButtonListener(this);

		// mFlashImageButton = (ImageButton)
		// findViewById(R.id.topbarRightButton);
		// mFlashImageButton.setTag("1");

		mHasSurface = false;
		mInactivityTimer = new InactivityTimer(this);
		mCameraManager = new CameraManager(getApplication());
		mViewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
		mViewfinderView.setCameraManager(mCameraManager);

		Bundle data = getIntent().getExtras();
		if (data != null && data.size() > 0) {
			mFlag = data.getString("flag");
		}
	}

	/**
	 * 主要对相机进行初始化工作
	 */
	@Override
	public void onResume() {

		mInactivityTimer.onActivity();
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (mHasSurface) {
			initCamera(surfaceHolder);
		} else {
			// 如果SurfaceView已经渲染完毕，会回调surfaceCreated，在surfaceCreated中调用initCamera()
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		// 恢复活动监控器
		mInactivityTimer.onResume();
		super.onResume();
	}

	public void drawViewfinder() {
		mViewfinderView.drawViewfinder();
	}

	/**
	 * 初始化摄像头。打开摄像头，检查摄像头是否被开启及是否被占用
	 * 
	 * @param surfaceHolder
	 */
	private void initCamera(SurfaceHolder surfaceHolder) {
		if (surfaceHolder == null) {
			throw new IllegalStateException("No SurfaceHolder provided");
		}
		if (mCameraManager.isOpen()) {
			return;
		}
		try {
			mCameraManager.openDriver(surfaceHolder);
			// Creating the mHandler starts the preview, which can also throw a
			// RuntimeException.
			if (mHandler == null) {
				mHandler = new CaptureActivityHandler(this, mDecodeFormats,
						CHARACTER_SET, mCameraManager);
			}
		} catch (IOException ioe) {
			displayFrameworkBugMessageAndExit();
		} catch (RuntimeException e) {
			// Barcode Scanner has seen crashes in the wild of this variety:
			// java.?lang.?RuntimeException: Fail to connect to camera service
			displayFrameworkBugMessageAndExit();
		}
	}

	/**
	 * 初始化照相机失败显示窗口
	 */
	private void displayFrameworkBugMessageAndExit() {
		MyDialog dialog = new MyDialog(this).setTitle(R.string.app_name)
				.setMessage("初始化照相机失败!")
				.setNegativeButtonSplitImageHide(true)
				.setPositiveButton(R.string.app_ok, new OnClickListener() {

					@Override
					public void onClick(View v) {
						finish(true);
					}
				});

		dialog.create(null);
		dialog.showMyDialog();
	}

	/**
	 * 暂停活动监控器,关闭摄像头
	 */
	@Override
	public void onPause() {
		if (mHandler != null) {
			mHandler.quitSynchronously();
			mHandler = null;
		}
		// 暂停活动监控器
		mInactivityTimer.onPause();
		// 关闭摄像头
		mCameraManager.closeDriver();
		if (!mHasSurface) {
			SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
			SurfaceHolder surfaceHolder = surfaceView.getHolder();
			surfaceHolder.removeCallback(this);
		}
		super.onPause();
	}

	/**
	 * 停止活动监控器,保存最后选中的扫描类型
	 */

	@Override
	public void onDestroy() {
		// 停止活动监控器
		mInactivityTimer.shutdown();
		super.onDestroy();
	}

	/**
	 * 获取扫描结果
	 * 
	 * @param rawResult
	 * @param barcode
	 * @param scaleFactor
	 */
	public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
		// mInactivityTimer.onActivity();
		boolean fromLiveScan = barcode != null;
		if (fromLiveScan) {

			// Then not from history, so beep/vibrate and we have an image to
			// draw on
		}
		// DateFormat formatter =
		// DateFormat.getDateTimeInstance(DateFormat.SHORT,
		// DateFormat.SHORT);
		Map<ResultMetadataType, Object> metadata = rawResult
				.getResultMetadata();
		StringBuilder metadataText = new StringBuilder(20);
		if (metadata != null) {
			for (Map.Entry<ResultMetadataType, Object> entry : metadata
					.entrySet()) {
				if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
					metadataText.append(entry.getValue()).append('\n');
				}
			}
			if (metadataText.length() > 0) {
				metadataText.setLength(metadataText.length() - 1);
			}
		}
		parseBarCode(rawResult.getText());
	}

	// 解析二维码
	private void parseBarCode(String msg) {
		// 手机震动
		Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		vibrator.vibrate(100);

		handleCodeResult(msg);

	}

	/*
	 * 处理扫描二维码结果
	 */
	private void handleCodeResult(String msg) {
		String resultMsg = parseChineseBarCode(msg);
		LogUtilBase.LogD(null, "二维码扫一扫结果======" + resultMsg);

		Intent intent = new Intent();
		if (!StringUtilBase.stringIsEmpty(mFlag)) {
			if (mFlag.equals(DoctorMyActivity.class.getName())) {
		        intent.putExtra("data", resultMsg);
			}
		}

		setResult(RESULT_OK,intent);
		finish(true);

	}

	private String parseChineseBarCode(String msg) {
		String UTF_Str = "";
		String GB_Str = "";
		boolean is_cN = false;
		try {
			UTF_Str = new String(msg.getBytes("ISO-8859-1"), "UTF-8");
			is_cN = IsChineseOrNot.isChineseCharacter(UTF_Str);
			// 防止有人特意使用乱码来生成二维码来判断的情况
			boolean b = IsChineseOrNot.isSpecialCharacter(msg);
			if (b) {
				is_cN = true;
			}
			if (!is_cN) {
				GB_Str = new String(msg.getBytes("ISO-8859-1"), "GB2312");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String resultMsg = "";
		if (is_cN) {
			resultMsg = UTF_Str;
		} else {
			resultMsg = GB_Str;
		}
		return resultMsg;
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (holder == null) {

		}
		if (!mHasSurface) {
			mHasSurface = true;
			initCamera(holder);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		mHasSurface = false;
	}

	/**
	 * 闪光灯调节器。自动检测环境光线强弱并决定是否开启闪光灯
	 */
	public ViewfinderView getViewfinderView() {
		return mViewfinderView;
	}

	public Handler getHandler() {
		return mHandler;
	}

	public CameraManager getCameraManager() {
		return mCameraManager;
	}

	/**
	 * 在经过一段延迟后重置相机以进行下一次扫描。 成功扫描过后可调用此方法立刻准备进行下次扫描
	 * 
	 * @param delayMS
	 */
	public void restartPreviewAfterDelay(long delayMS) {
		if (mHandler != null) {
			mHandler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
		}
	}

	/**
	 * 闪光灯设置
	 */
	@SuppressWarnings("unused")
	private void setFlash() {

		if (mFlashImageButton.getTag() != null) {
			mCameraManager.setTorch(true);
			mFlashImageButton.setTag(null);
			mFlashImageButton.setBackgroundResource(R.drawable.flash_open);
		} else {
			mCameraManager.setTorch(false);
			mFlashImageButton.setTag("1");
			mFlashImageButton.setBackgroundResource(R.drawable.flash_default);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == BACK_PHOTO) {

				Uri uri = data.getData();
				String imgPath = ImageUtilBase.getImageAbsolutePath(CaptureActivity.this, uri);
				
				Bitmap bitmap = ImageUtilBase.getBitmap(imgPath);

				Result rawResult = decodePhoto(bitmap);
				if (rawResult == null) {
					UIHelper.showToast(CaptureActivity.this,
							"错误的二维码");
					return;
				}

				handleCodeResult(rawResult.getText());
			}
		}
	}

	private Result decodePhoto(Bitmap bitmap) {
		MultiFormatReader multiFormatReader = new MultiFormatReader();

		// 解码的参数
		Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(
				2);
		// 可以解析的编码类型
		Vector<BarcodeFormat> mDecodeFormats = new Vector<BarcodeFormat>();
		if (mDecodeFormats == null || mDecodeFormats.isEmpty()) {
			mDecodeFormats = new Vector<BarcodeFormat>();

			// 这里设置可扫描的类型，选择了都支持
			mDecodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);
			mDecodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
			mDecodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);
		}
		hints.put(DecodeHintType.POSSIBLE_FORMATS, mDecodeFormats);

		// 设置继续的字符编码格式为UTF8
		// hints.put(DecodeHintType.CHARACTER_SET, "UTF8");

		// 设置解析配置参数
		multiFormatReader.setHints(hints);

		// 开始对图像资源解码
		Result rawResult = null;
		try {
			rawResult = multiFormatReader.decodeWithState(new BinaryBitmap(
					new HybridBinarizer(new BitmapLuminanceSource(bitmap))));
		} catch (NotFoundException e) {
			e.printStackTrace();
		}
		return rawResult;
	}

	@Override
	public void onBackPressed() {
		// test
		// 方便用电阻条测试，省的每次扫描二维码
		// if(Utils.DEBUG)
		// {
		// setResult(RESULT_OK);
		// }

		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		// test
		// 方便用电阻条测试，省的每次扫描二维码
		// if(Utils.DEBUG)
		// {
		// setResult(RESULT_OK);
		// }
		finish(true);
	}

	@Override
	public void onTopbarRightButtonSelected() {
		// setFlash();去掉闪光灯

		Intent photo = new Intent(Intent.ACTION_GET_CONTENT, null);
		photo.setType("image/*");
		photo.putExtra("return-data", true);
		startActivityForResult(photo, BACK_PHOTO, true);
	}
}
